/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.velocityme.session;

import com.velocityme.entity.ChangeDelta;
import com.velocityme.entity.Issue;
import com.velocityme.enums.ChangeDeltaType;
import com.velocityme.enums.Permission;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 *
 * @author rcrida
 */
@Stateless
public class IssueBean implements IssueLocal {
    @EJB
    private ActivityLocal activityBean;

    @PersistenceContext
    private EntityManager em;

    public Issue findIssue(KeyLocal key, Long issueId) {
        Issue issue = em.find(Issue.class, issueId);
        key.assertHasPermission(issue, Permission.NODE_VIEW);
        return issue;
    }
    
    public Issue createIssue(KeyLocal key, Issue issue, boolean interested) {
        key.assertHasPermission(issue.getParentNode(), Permission.ISSUE_CREATE);
        ChangeDelta changeDelta = issue.addChangeDelta(ChangeDeltaType.CREATE, key.getUser());
        activityBean.logCreate(key, issue, changeDelta, interested);
        em.persist(issue);
        em.persist(changeDelta);
        return issue;
    }

    public void editIssue(KeyLocal key, Issue issue) {
        Issue current = em.find(Issue.class, issue.getId());
        key.assertHasPermission(issue, Permission.ISSUE_EDIT);
        ChangeDelta changeDelta = issue.addChangeDelta(ChangeDeltaType.EDIT, key.getUser());
        activityBean.logEdit(key, issue, current, changeDelta);
        em.persist(changeDelta);
        em.merge(issue);
    }

}
